#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <curl/curl.h>
#include "comm.h"
#include "config.h"
#include "manage.h"
#include "crawl.h"

MANAGE_TH_ARG man_th_arg;
pthread_t man_th;
pthread_t *thread;
CRAWL_TH_ARG *thread_arg;
pthread_rwlock_t conf_lock = PTHREAD_RWLOCK_INITIALIZER;

int main(int argc, char **argv)
{
	char *conf_file = argv[1];
	if (conf_file != NULL) {
		strncpy(man_th_arg.conf_file, conf_file, sizeof(man_th_arg.conf_file) - 1);
	}
	else {
		printf("usage: %s conf_file\n", argv[0]);
		return 1;
	}
	if (init(conf_file) != 0)
		return 1;

	CURLcode ret = curl_global_init(CURL_GLOBAL_ALL);
	if (ret != 0) {
		printf("curl_global_init: %s\n", curl_easy_strerror(ret));
		return 1;
	}

	/////////////////////////////////////////////
	//抓取线程相关代码
	//crawl.c
	thread = (pthread_t *)malloc(conf.threads_num * sizeof(pthread_t));
	thread_arg = (CRAWL_TH_ARG *)malloc(conf.threads_num * sizeof(CRAWL_TH_ARG));
	for (int i = 0; i < conf.threads_num; i++) {
		thread_arg[i].conf = &conf;
		pthread_create(&thread[i], NULL, crawl_thread, &thread_arg[i]);
	}

	/*
	 * create manage thread
	 **/
	int err = pthread_create(&man_th, NULL, manage_thread, &man_th_arg);
	if (err != 0) {
		fprintf(stderr, "pthread_create: %s\n", strerror(err));
	}

	/*
	 * 如何使配置在多个线程中生效？2009-08-12
	 * ******************************************
	 * */

	pthread_join(man_th, NULL);
	pthread_rwlock_wrlock(&conf_lock);
	conf.cmd = CONF_QUIT;
	pthread_rwlock_unlock(&conf_lock);
	for (int i = 0; i < conf.threads_num; i++) {
		pthread_join(thread[i], NULL);
	}
	return 0;
}
